﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StyleMVVM.Logging;
using StyleMVVM.View;
using Windows.System.Threading;
using Windows.UI.Core;
using Windows.UI.Xaml;

namespace StyleMVVM.Utilities
{
	public sealed class BackgroundTimer
	{
		private static readonly string supplemental = typeof(BackgroundTimer).FullName;
		private DispatcherTimer timer;

		public BackgroundTimer()
		{
			ViewHelper.MainDispatcher.RunAsync(CoreDispatcherPriority.Normal,
			                                   () =>
				                                   {
					                                   timer = new DispatcherTimer();
					                                   timer.Interval = Interval;

					                                   timer.Tick += TimerOnTick;
					                                   timer.Start();
				                                   });
		}

		public event EventHandler<object> Tick;

		public TimeSpan Interval { get; set; }

		public void Start()
		{
			if (timer != null)
			{
				timer.Start();
			}
		}

		public void Stop()
		{
			if (timer != null)
			{
				timer.Stop();
			}
		}

		private void TimerOnTick(object sender, object o)
		{
			ThreadPool.RunAsync(x =>
				                    {
					                    try
					                    {
						                    Tick(this, null);
					                    }
					                    catch (Exception exp)
					                    {
						                    Logger.Error("Exception thrown from background timer when calling Tick", supplemental, exp);
					                    }
				                    });
		}
	}
}